package com.ruoyi.framework.auth2;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class OAuth2Authentication {
	// 使用默认请求方式
    @Autowired
    @Qualifier(value = "restTemplate")
    private RestTemplate restTemplate;
	String clientId = "1515908819811618818";
	String clientSecret = "ff80808180293b6701803ae88eac0a9d";
	String accessTokenUrl = " http://i.njupt.edu.cn/cas/oauth2.0/accessToken";
	String redirectUrl = "https://sysxcx.njupt.edu.cn/";
	String profileUrl = "http://i.njupt.edu.cn/cas/oauth2.0/profile";
	private final Log log = LogFactory.getLog(OAuth2Authentication.class);
	
	public AccessToken getAccessToken(String code){
		OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
		try {
			OAuthClientRequest accessTokenRequest = OAuthClientRequest
					.tokenLocation(accessTokenUrl)
					.setGrantType(GrantType.AUTHORIZATION_CODE)
					.setClientId(clientId)
					.setClientSecret(clientSecret)
					.setCode(code)
					.setRedirectURI(redirectUrl)
					.buildQueryMessage();
			// 去服务端请求access token，并返回响应
			OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.GET);
			AccessToken token = new AccessToken();
			token.setName(oAuthResponse.getAccessToken());
			token.setExpiresIn(oAuthResponse.getExpiresIn());
			return token;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	@SuppressWarnings("rawtypes")
	public String getUserId(String accessToken){
		Map userInfo = restTemplate.getForObject(profileUrl+"?access_token="+accessToken, Map.class);
		return userInfo.get("id").toString();
	}

}
